<?php
namespace app\admin\controller;
use app\admin\model\Address;
use app\admin\model\User as UserModel;
use app\admin\model\Teacher;
use app\admin\model\Student as StudentModel;
use think\Controller;
use think\Db;
use app\admin\model\Coin;
use app\admin\model\ Address as AddressModel;
use app\admin\validate\User as UserValidate;

class Member extends UserAuth{
    public function index(){

        return $this->fetch('index');
    }

    /**
     * 会员列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function member_list(){
        if (request()->isGet()) {

            $member = (new UserModel())->getAll();
            $count = (new UserModel())->getCount();
            $this->assign('count',$count);
            $this->assign('member',$member);
        }

        return $this->fetch('member_list');
    }

    /**
     * 会员详细信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function member_show($id){

        $user = (new UserModel())->getUserById($id);

        $this->assign('user',$user);
        return $this->fetch('member_show');
    }

    /**
     * 添加会员
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|mixed|string|\think\response\Json
     */
    public function add_member(){
        $province = Db::name('province')->select();
        //新增会员角色下拉选项值
       
        $user_auth = Db::name('auth_group')->field('id,title')->select();
       
        if(request()->isAjax()){
            $data = $_POST;

            //验证
            $validate = validate('user');
            if(!$validate->scene('add_member')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            Db::startTrans();
            try{

                if(!empty($_FILES)){
                    $images = uploadImage('user_images');
                    if(is_object($images)){
                        return $images;
                    }else{
                        $data['user_images'] = $images;
                    }
                }else{
                    $data['user_images'] = '';
                }

                $data['ctime'] = time();
                $data['password'] = md5($data['password']);
                $userModel = new UserModel($data);
                $add = $userModel
                    ->allowField(true)
                    ->save($data);
                $user_id = $userModel->id;

                if($add){
                    if($data['area_code']&&$data['address']){
                        $address = new AddressModel();
                        $address->member_id =  $user_id;
                        $address->area_code = $data['area_code'];
                        $address->address = $data['address'];
                        $res= $address->save();
                    }elseif($data['area_code']){
                        $address = new AddressModel();
                        $address->member_id =  $user_id;
                        $address->area_code = $data['area_code'];
                        $res= $address->save();
                    }elseif($data['address']){
                        $address = new AddressModel();
                        $address->member_id =  $user_id;
                        $address->address = $data['address'];
                        $res= $address->save();
                    }else{
                        $address = new AddressModel();
                        $address->member_id =  $user_id;
                        $res= $address->save();
                    }

                    if($res){
                        if($data['user_auth'] == 3){
                            $student = new StudentModel();
                            $student->student_id = $user_id;
                            $student->save();

                        }else if($data['user_auth'] == 2){
                            $teacher = new Teacher();
                            $teacher->teacher_id = $user_id;
                            $teacher->save();
                        }
                        Db::commit();// 事务提交
                        return show(config('code.success'),'新增会员成功!！');
                    }
                }else{
                    return show(config('code.error'),'新增会员失败！');
                }
            }catch (\Exception $e){
                Db::rollback();// 事务回滚
                return show(config('code.error'),'新增会员失败!！');
            }
        }
        $this->assign('province',$province);
        $this->assign('user_auth',$user_auth);
        return $this->fetch('add_member');
    }

    // 获取市
    public function city(){
        if(request()->isAjax()){
            $city=Db::name("city")->where(array('provincecode'=>input("post.provincecode")))->select();
            return $city;
        }
    }
    // 获取县
    public function area(){
        if(request()->isAjax()){
            $area=Db::name("area")->where(array('citycode'=>input("post.citycode")))->select();
            return $area;
        }
    }


    /**
     * 修改会员
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|mixed|string|\think\response\Json
     */
    public function edit_member($id){
        $user = Db::name('user')
            ->where('id='.$id)
            ->find();
        $user_auth = Db::name('auth_group')
            ->select();
        $users = Db::name("user")->select();
        if(request()->isAjax()){
            $data = $_POST;

            //支付密码
            if(isset($data['pay_password'])){
                $data['pay_password'] = md5($data['pay_password']);
            }

            //验证
            $validate = new UserValidate();
            if(!$validate->scene('edit_member')->check($data)){
                return show(config('code.error'),$validate->getError());
            }
            $img = Db::name('user')
                ->where('id='.$data['id'])
                ->field('user_images')
                ->find();

            try{
                if(!empty($_FILES)){
                    $images = uploadImage('user_images');
                    if(is_object($images)){
                        return $images;
                    }else{
                        $data['user_images'] = $images;
                    }
                }else{
                    //修改时未上传则删除空数据
                    unset($data['user_images']);
                }

                $user = new UserModel();
                $res = $user->allowField(true)->where('id='.$data['id']) ->update($data);
                if($res){
                    if(!empty($_FILES)){
                        if(!empty($img['user_images'])){
                            delImages($img['user_images']);
                            //检查父级目录是否为空并删除空目录
                            checkFileParentDir($img['user_images']);
                        }
                    }

                    return show(config('code.success'),'修改成功！');
                }else{
                    return show(config('code.error'),'修改失败！');
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }

        $this->assign('user',$user);
        $this->assign('users',$users);
        $this->assign('user_auth',$user_auth);
        return $this->fetch('edit_member');
    }
    /**
     * 删除会员
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function del_member(){
        if(request()->isAjax()){
            try{
                $id = $_POST['id'];

                $img = Db::name('user')
                    ->where('id='.$_POST['id'])
                    ->field('id,user_images,user_auth')
                    ->find();

                $user = new UserModel();
                $res = $user
                    ->where('id='.$id)
                    ->delete();

                if($res){
                    if(!empty($img['user_images'])){
                        delImages($img['user_images']);
                        //检查父级目录是否为空并删除空目录
                        checkFileParentDir($img['user_images']);
                    }
                    return show(config('code.success'),'删除成功');
                }else{
                    return show(config('code.error'),'删除失败');
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }
    /**
     * 批量删除会员
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function batch_del_member(){
        if(request()->isAjax()){
            try{
                if(!empty($_POST['id'])) {
                    $arr_id = $_POST['id'];
                    $str = implode(',', $arr_id);

                    $img = [];
                    foreach ($arr_id as $key => $val) {
                        $img[$key] = Db::name('user')
                            ->where('id', $val)
                            ->field('user_images')
                            ->find();
                    }



                    $del = Db::name('user')
                        ->where('id', 'in', $str)
                        ->delete();
                    if($del){
                        if(!empty($img)){
                            foreach ($img as $key => $val){
                                if (!empty($val['user_images'])) {
                                    delImages($val['user_images']);
                                    //检查父级目录是否为空并删除空目录
                                    checkFileParentDir($val['user_images']);
                                }
                            }
                        }
                        return show(config('code.success'), '删除成功');
                    }else{
                        return show(config('code.error'),'删除失败');
                    }
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }
    /**
     * 修改密码
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|mixed|string|\think\response\Json
     */
    public function edit_password($id){
        $user = Db::name('user')
            ->where('id='.$id)
            ->field('id,username')
            ->find();
        if(request()->isAjax()){
            try{
                $pass = Db::name('user')
                    ->where('id='.$_POST['id'])
                    ->field('password')
                    ->find();

                if($pass['password'] != md5($_POST['now_password'])){
                    return show(config('code.error'),'原始密码不正确！');
                }else if($pass['password'] == md5($_POST['now_password'])){
                    if($_POST['repassword'] != $_POST['password']){
                        return show(config('code.error'),'两次密码不一致！');
                    }else if($_POST['repassword'] == $_POST['password']){
                        $data['password'] = md5($_POST['password']);
                        $user = new UserModel();
                        $res = $user
                            ->allowField(true)
                            ->where('id='.$_POST['id'])
                            ->update($data);
                        if($res){
                            return show(config('code.success'),'修改成功！');
                        }else{
                            return show(config('code.error'),'修改失败！');
                        }
                    }
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
        $this->assign('user',$user);
        return $this->fetch('edit_password');
    }


    /**
     * 会员停用
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function stop_member(){
        if(request()->isAjax()){
            try{
                $data = $_POST;
                $user = Db::name('user')
                    ->where('id='.$data['id'])
                    ->find();
                if($user['stop_status'] == 1){
                    $data['stop_status'] = 0;
                    $user_model = new UserModel();
                    $res = $user_model
                        ->where('id='.$data['id'])
                        ->update($data);
                    if($res){
                        return show(config('code.success'),'已停用！');
                    }else{
                        return show(config('code.error'),'停用失败！');
                    }
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }

    /**
     * 会员启用
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function start_member(){
        try{
            if(request()->isAjax()){
                $data = $_POST;
                $user = Db::name('user')
                    ->where('id='.$data['id'])
                    ->find();
                if($user['stop_status'] == 0){
                    $data['stop_status'] = 1;
                    $user_model = new UserModel();
                    $res = $user_model
                        ->where('id='.$data['id'])
                        ->update($data);
                    if($res){
                        return show(config('code.success'),'已启用！');
                    }else{
                        return show(config('code.error'),'启用失败！');
                    }
                }
            }
        }catch (\Exception $e){
            return show(config('code.error'),$e->getMessage(),[],500);
        }
    }


    /**
     * 导出会员列表
     * @author 巫玉梅 <1120504614@qq.com>
     * @return
     */
    public function export_member_excel(){
        $data =  Db::name('user')
            ->alias('u')
            ->join('auth_group group','user_auth=group.id','LEFT')
            ->field('u.id,u.username,u.full_name,u.user_images,u.tel,
                    u.sex,group.title,u.ctime,u.stop_status,group.title')
            ->select();
        $str = "";
        for($i = 0;$i < count($data); $i++){
            $str .= "<tr>";
            $str .= "<td>".($i+1)."</td>";
            $str .= "<td>".$data[$i]["username"]."</td>";
            $str .= "<td>".$data[$i]["full_name"]."</td>";
            $str .= "<td>".$data[$i]["tel"]."</td>";
            $str .= "<td>".$data[$i]["sex"]."</td>";
            $str .= "<td>".$data[$i]["ctime"]."</td>";
            $str .= "</tr>";
        }

        header("Content-type:text/html;charset=utf-8");
        header("Content-Disposition:attachment;filename=用户信息.xls");

        echo "
            <!DOCTYPE html>
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
            <title>用户信息表</title>
            <style>
                td{
                    text-align:center;
                    font-size:12px;
                    color: black;
                    border:black 1px solid;
                }
                table,tr{
                    border-style:none;
                }
                .title{
                    color:black;font-weight:bold;
                }
            </style>
            </head>
            <body>
            <table border='1'>
              <tr>
                <td class='title'>序号</td>
                <td class='title'>用户名</td>
                <td class='title'>姓名</td>
                <td class='title'>手机</td>
                <td class='title'>性别</td>
                <td class='title'>注册时间</td>
              </tr>
              ".$str."
            </table>
            </body>
            </html>
        ";
    }
}
